package pe.com.hermes.hermetic.negocio.serviceimpl;

import pe.com.hermes.hermetic.beans.ClienteBean;
import pe.com.hermes.hermetic.beans.User;

import pe.com.hermes.hermetic.negocio.service.TablService;

import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Collection;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import pe.com.hermes.hermetic.beans.CorporacionBean;
import pe.com.hermes.hermetic.beans.UsuCodBancoBean;

@Service("userDetailsService")
public class UserServiceImpl implements UserDetailsService{
    private Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private TablService tablService; 
    
    public UserDetails loadUserByUsername(String usernameAndCompany) throws UsernameNotFoundException, DataAccessException{
        User user = null;
        try{
            String[] userAndCompany = usernameAndCompany.split(",");
            String usuWeb =  userAndCompany[0];
            int codRazoSoci =  Integer.parseInt(userAndCompany[1]);
            CorporacionBean corporacionBean=new CorporacionBean();
            UsuCodBancoBean usuCodBancoBean=new UsuCodBancoBean();
            String[]codClies=null;
            
            user = tablService.getUserByName(usuWeb);
            if(user==null)
                throw new UsernameNotFoundException(usernameAndCompany);
            user.setPerfil(tablService.getPerfByUsernameAndCodRazoSoci(user.getUsuWeb(),user.getCodRazoSoci()));
            user.setListClie(tablService.getClieByUser(user.getUsuWeb()));
            user.setAuthorities(tablService.getRolesByPerf(user.getPerfil(),"HW"));
            user.getAuthorities().add(new GrantedAuthorityImpl("ROLE_USER"));
            List<ClienteBean> listClie = user.getListClie();
            for(ClienteBean clienteBean : listClie){
                if(clienteBean.getCodRazoSoci()==codRazoSoci){
                    user.setCodRazoSoci(clienteBean.getCodRazoSoci());
                    user.setNomClie(clienteBean.getNomClie());
                    user.setCodClie(String.valueOf(clienteBean.getCodClie()));
                }
                if(clienteBean.getCodRazoSoci()==237)
                    user.getAuthorities().add(new GrantedAuthorityImpl("ROLE_HERME"));
            }
            corporacionBean = tablService.getCorporacionUsu(user.getUsuWeb(),user.getCodRazoSoci());
            if(corporacionBean.getCod_corp()==0)
             usuCodBancoBean = tablService.getUsuCodBanco(user.getCodRazoSoci(),user.getCodSucuHtb());
            else if(corporacionBean.getCod_corp()>0)
              usuCodBancoBean = tablService.getUsuCodBancoCorp(corporacionBean.getCod_corp(),user.getCodSucuHtb());
            
            user.setDesRazoSoci(tablService.getRazSocial(user.getUsuWeb(),user.getCodRazoSoci()));
            user.setCodCorp(corporacionBean.getCod_corp());
            user.setDesCorp((corporacionBean.getDes_corp()==null)?"":corporacionBean.getDes_corp());
            user.setBoveBanc(usuCodBancoBean.getBoveBanc());
            user.setBoveProp(usuCodBancoBean.getBoveProp());
            user.setDiaHab(usuCodBancoBean.getDiaHab());
            user.setSusAnom(usuCodBancoBean.getSusAnom());
            user.setDifFecContAt(usuCodBancoBean.getDifFecContAt());
            user.setDifFecContPed(usuCodBancoBean.getDifFecContPed());
            user.setAlertPen(usuCodBancoBean.getAlertPen());
            user.setHorAlertPen(usuCodBancoBean.getHorAlertPen());
            user.setAprAutPed(usuCodBancoBean.getAprAutPed());
            user.setFaseAbono(usuCodBancoBean.getFaseAbono());
            user.setValiParm(usuCodBancoBean.getValiParm());
            
            user.setListCodUsu((usuCodBancoBean.getListUsu()==null)?"":usuCodBancoBean.getListUsu());
            
            if(corporacionBean.getCod_corp()!=0)
              user.setTipClie(0);
            else{
                if(usuCodBancoBean.getListUsu()!=null){
                  codClies = usuCodBancoBean.getListUsu().split(",");
                  if(codClies.length>1)
                    user.setTipClie(2);
                  else if(codClies.length==1){
                      user.setTipClie(tablService.getTipClie(codClies[0]));   
                  }
                }
            }
            logger.info("codigo sucursal = "+user.getCodSucuHtb());
            logger.info("parametros incorporados: ");
            logger.info("razon social = "+user.getDesRazoSoci());
            logger.info("codigo corporacion = "+corporacionBean.getCod_corp());
            logger.info("descripcion corporacion = "+((corporacionBean.getDes_corp()==null)?"":corporacionBean.getDes_corp()));
            logger.info("boveda banco = "+usuCodBancoBean.getBoveBanc());
            logger.info("boveda propia = "+usuCodBancoBean.getBoveProp());
            logger.info("lista de codigos = "+((usuCodBancoBean.getListUsu()==null)?"":usuCodBancoBean.getListUsu()));
            logger.info("tipo de cliente = "+user.getTipClie());
        }catch(SQLException e){
            logger.error(e);
            user=null;
        }
        return user;
    }

    public void setTablService(TablService tablService) {
        this.tablService = tablService;
    }
}
